//



//google maps
var directionDisp;
var directionsServ = new google.maps.DirectionsService();
var ma;
var geoco;
var originalLocations;
var originalDates;
//This will load the Map when Ready
$(document).ready(function(){
    init_Mini();
    
    for(var t = 0; t < wayDates.length; t++){
        wayDates[t] = parseDateToPicker(wayDates[t]);
        originalLocations +='&wayPtLocationOriginal=' + wayPoints[i];
        originalDates += '&wayPtDateOriginal=' + wayDates[i];
    }
    
    loadWaypoints();
    
    $("#tripStart").attr("value",startLocation);
    $("#tripEnd").attr("value",endLocation);
    $("#tripStartDate").attr("value",parseDateToPicker(startDate));
    $("#tripEndDate").attr("value",parseDateToPicker(endDate));
    
    
});
//This has all the proper code to do the assignment in 308 + find the specific location
function init_Mini() {
    directionsDisp = new google.maps.DirectionsRenderer();
    geoco = new google.maps.Geocoder()
    var chicago = new google.maps.LatLng(41.850033, -87.6500523);
    var mapOptions = {
        zoom: 6,
        mapTypeId: google.maps.MapTypeId.TERRAIN,
        center:chicago
    }
    ma = new google.maps.Map(document.getElementById('wayPointMap'), mapOptions);
    directionsDisp.setMap(ma);
}
//Sample call
//$("#startButton").click(function(){
//  codeAddress("start");
//});
//Code for getting the address and updating the map

var markers = []
var startMarker = [];
var endMarker = [];


function codeAddressWay(tagId) {
    
    //var greenIcon = new GIcon(G_DEFAULT_ICON);
   
   
    var greenIconFile =  "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png";
    var redIconFile = "http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png";
    
    var marker;
   /* if(markers.length > 0)
    { 
        //markers.pop().setMap(null); 
        temp = [];
       // var mark = markers.pop();
        while(mark != null){
            mark.setIcon(redIconFile);
            temp.push(mark);
            mark = markers.pop();
        }
        markers = temp;
    }*/
    var address = document.getElementById(tagId).value;
    geoco.geocode( {
        'address': address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            ma.setCenter(results[0].geometry.location);    
            marker = new google.maps.Marker({
                map: ma,
                position: results[0].geometry.location
            });
            marker.setIcon(greenIconFile);
            // markers.push(marker);
            if(wayPoints.length <= 0)
            {
                wayPoints[0] = results[0].formatted_address;
                wayDates[0] = $("#tripWaypointDate").val();
                markers[0] = marker;
            //alert(wayPoints[0]);
            }
            else
            {
                var val = addToWayPtList(results[0].formatted_address, $("#tripWaypointDate").val());
                addToMarkerList(marker,val);
            }
            loadWaypoints();
        $("#tripWaypoint").val("");
        $("#tripWaypointDate").val("");   
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        //mark = markers.pop();
        //mark.setMap(null);
        }
    });
}
   
function codeAddressWayEdit(tagId,index) {
    // alert("alert'd");
    //var greenIcon = new GIcon(G_DEFAULT_ICON);
    var greenIconFile =  "http://www.google.com/intl/en_us/mafiles/ms/micons/green-dot.png";
    var redIconFile = "http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png";
    var marker;
    var loc;
   /* if(markers.length > 0) // SET THE OLD MARKERS TO RED
    { 
        for(var k = 0; k < markers.length; k++){
            if(k != index){
                markers[k].setIcon(redIconFile);
            }
        }
    }*/
    var address = document.getElementById(tagId).value;
    geoco.geocode( {
        'address': address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            ma.setCenter(results[0].geometry.location);    
            marker = new google.maps.Marker({
                map: ma,
                position: results[0].geometry.location
            });
            marker.setIcon(greenIconFile);
            if(wayPoints.length <= 0)
            {
                wayPoints[index] = results[0].formatted_address;
                wayDates[index] = $("#date" + index).val();
            //    markers[index] =  marker;
            }
            else
            {
                var val = addToWayPtList(results[0].formatted_address, $("#date" + index).val());
            //addToMarkerList(marker,val);
            }
            loadWaypoints();
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        //mark = markers.pop();
        //mark.setMap(null);
        }
    });
    return loc;
}
function addToMarkerList(marker,index){
    var temp = [];
    for(var x = 0; x < index; x++){
        temp[x] = markers[x];
    }
    temp[index] = marker;
    for(var x = index; x < markers.length; x++){
        temp[x+1] = markers[x];
    }
    markers = temp;
}

function codeAddressStartEnd(tagId) {
    
    //var greenIcon = new GIcon(G_DEFAULT_ICON);
   
   
    var startIconFile = "http://www.google.com/intl/en_us/mapfiles/ms/micons/yellow-dot.png";
    var endIconFile = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
    
    var marker;
    var address = document.getElementById(tagId).value;
    geoco.geocode( {
        'address': address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            ma.setCenter(results[0].geometry.location);    
            marker = new google.maps.Marker({
                map: ma,
                position: results[0].geometry.location
            });
            if(tagId == "tripStart"){
                marker.setIcon(startIconFile);
                startMarker.push(marker);
                $("#" + tagId).val(results[0].formatted_address); 
                startLocation = results[0].formatted_address;
                $("#tripStart").val(startLocation);
            }
            else{
                marker.setIcon(endIconFile);
                $("#" + tagId).val(results[0].formatted_address); 
                endMarker.push(marker);
                endLocation = results[0].formatted_address;
                
                $("#tripEnd").val(endLocation);
            }  
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
       
    });
}



//add variables for startLocation, startDate, endLocation, endDate, wayPointLocation, wayPointDate (array for these two)
//method for the add buttons - display location on map and add to array and display in right
//make location clickable on the right 


var i = 0;
function doDatePicker(tagId){
    jQuery(function() {
        jQuery(tagId).datePicker();
    });
}

jQuery(function() {
    jQuery( "#tripStartDate" ).datepicker();
    jQuery( "#tripEndDate" ).datepicker();
    jQuery( "#tripWaypointDate" ).datepicker();
});

function loadWaypoints(){
    var html = "<ol>";
    for(var x = 0; x < wayPoints.length; x++){
        html += "<li>"  + (x != 0?"<input type='button' value='&#9650' onclick='moveUp(" + x + ")' />":"<input type='button' value='&#9651'/>")
        +(x != wayPoints.length-1?"<input type='button' value='&#9660' onclick='moveDown(" + x + ") '/>":"<input type='button' value='&#9661'/>") 
        +"&nbsp;" + "<input class='tripInput' id='trip" + x + "' type='text' value='"+wayPoints[x]+"' readonly='readonly' />" 
        + "|&nbsp;<input class='tripInput2' id='date" + x + "' type='text' value='"+ wayDates[x] +"' readonly='readonly' onfocus='doDatePicker(#date'" + x + ")'/>"
        + "<input type='button' onclick='edit(" + x + ")' value='Edit'/>" 
        + "<input type='button' id='saveButton"+ x +"' class='invisible' onclick='save(" + x + ")' value='Save'/>"
        + "<input type='button' onclick='deleteWayPoint(" + x + ")' value='Delete' />" 
        + "</li><br/>";
    }
    html += "</ol>"
    $("#waypointDiv").html(html);
}

function edit(num){
    var id = "#trip" +  num;
    $(id).removeAttr("readonly");
    $(id).css("border-style","groove");
    $(id).css("background-color","#FFFFFF");
    
    id = "#date" +  num;
    $(id).removeAttr("readonly");
    $(id).css("border-style","groove");
    $(id).css("background-color","#FFFFFF");
    
    $("#saveButton" + num).css("display","inline");
    
}

function save(num){
    //MAKE READONLY
    var id = "#trip" + num;
    $(id).attr("readonly","readonly");
    $(id).css("border-style","none");
    
    $(id).css("background-color","#E8EAEC");
    
    id = "#date" + num;
    $(id).attr("readonly","readonly");
    $(id).css("border-style","none");
    
    $(id).css("background-color","#E8EAEC");
    
    //////////////////
    var temp = []; //Take in old list
    for(var x = 0; x < num; x++){
        temp[x] = wayPoints[x];
    }
    //SKIP THE ONE WE'RE EDITING (will maintain order)
    for(var x = num+1; x < wayPoints.length; x++){
        temp[x-1] = wayPoints[x];
    }
    wayPoints = temp;
    temp = [];
    for(var x = 0; x < num; x++){
        temp[x] = wayDates[x];
    }
    for(var x = num+1; x < wayDates.length; x++){
        temp[x-1] = wayDates[x];
    }
    wayDates = temp;
    //Markers
    // markers[num].setMap(null); //REMOVE EDITED MARKER
    ///////////////////
    codeAddressWayEdit("trip" + num, num); // ADD into the list
    $("#saveButton" + num).css("display","none");
}

function deleteWayPoint(num){
    //Locations
    var temp = [];
    for(var p = 0; p < num; p++){
        temp.push(wayPoints[p]);
    }
    for(var j = num+1; j < wayPoints.length; j++){
        temp.push(wayPoints[j]);
    }
    //wayPoints.pop(num);
    wayPoints = [];
    wayPoints = temp;
    //Dates
    temp = [];
    for(var x = 0; x < num; x++){
        temp.push(wayDates[x]);
    }
    for(var y = num+1; y < wayDates.length; y++){
        temp.push(wayDates[y]);
    }
    wayDates = [];
    wayDates  = temp;
    
    //wayDates.pop(num);
    temp = [];
    //Markers
    //markers[num].setMap(null);
    //for(var k = 0; k < num; k++){
    //    temp.push(markers[k]);
   // }
   // for(var l = num+1; l < markers.length; l++){
   //     temp.push(markers[l]);
   // }
  //  markers = temp;
    i--;
    loadWaypoints();
}

function moveUp(pos){
    
    if(checkDate(wayDates[pos],wayDates[pos-1]) == 0){
        var temp = wayPoints[pos-1];
        wayPoints[pos-1] = wayPoints[pos];
        wayPoints[pos] = temp;
        //Move Date too
        temp = wayDates[pos-1];
        wayDates[pos-1]  = wayDates[pos];
        wayDates[pos] = temp;
        //Markers
        temp = markers[pos-1];
        markers[pos-1]  = markers[pos];
        markers[pos] = temp;
        loadWaypoints();
    }
}

function moveDown(pos){
    if(checkDate(wayDates[pos],wayDates[pos+1]) == 0){
        var temp = wayPoints[pos+1];
        wayPoints[pos+1] = wayPoints[pos];
        wayPoints[pos] = temp;
        //Move Date too
        temp = wayDates[pos+1];
        wayDates[pos+1]  = wayDates[pos];
        wayDates[pos] = temp;
        //Markers
        temp = markers[pos+1];
        markers[pos+1]  = markers[pos];
        markers[pos] = temp;
        loadWaypoints();
    }
}

function addStart()
{
    var tempEnd = $("#tripEndDate").val().trim();
    
    
    startLocation = document.getElementById("tripStart").value;
    startDate = document.getElementById("tripStartDate").value;
    

    if(checkDate(tempEnd, startDate)  > -1 || tempEnd == "")
    {
        if(startMarker.length > 0){
            var m = startMarker.pop();
            m.setMap(null);
        }
        
        
        
        codeAddressStartEnd("tripStart");
    ///  $("#addStart").attr('src',"images/UpdateButton.png");
    // $("#addStart").attr("alt","update");
        
    }
    else
    {
        alert("Can not insert because of date discrepencies.");
    }
    
}

function checkDate(date1, date2)
{
    var date1yr, date1mo, date1day;
    var date2yr, date2mo, date2day;
    
    //  MM/DD/YYYY
    date1mo = date1.substring(0,2);
    date2mo = date2.substring(0,2);
    date1day = date1.substring(3,5);
    date2day = date2.substring(3,5);
    date1yr = date1.substring(6);
    date2yr = date2.substring(6);
    
    //alert("DATE1:"+date1mo +" " +date1day + " "+date1yr + ",  DATE2:" + date2mo + date2day + date2yr);
    
    date1mo = parseInt(date1mo,10);
    date1day = parseInt(date1day,10);
    date1yr = parseInt(date1yr,10);
    
    date2mo = parseInt(date2mo,10);
    date2day = parseInt(date2day,10);
    date2yr = parseInt(date2yr,10);
    
    var b = 0;
    if(date1yr > date2yr){
        return 1;
    }
    else if(date1yr == date2yr){
        if(date1mo > date2mo){
            return 1;
        }
        else if(date1mo == date2mo){
            if(date1day > date2day){
                return 1;
            }
            else if(date1day == date2day){
                return 0;
            }
            else{
                return -1;
            }
        }
        else{
            return -1;
        }
    }
    else{
        return -1; //true if date 1 is later than date 2 . date2 before date1 
    }
}
function addEnd()
{
    endDate = document.getElementById("tripEndDate").value;
    
    var tempStart = $("#tripStartDate").val().trim();
    
    if(tempStart == "" || checkDate(endDate, tempStart) > -1)
    {
        if(endMarker.length > 0){
            var m = endMarker.pop();
            m.setMap(null);
        }
        codeAddressStartEnd("tripEnd");
    // $("#endSpan").html("End: <span class='sizeEighteen' >"+endLocation + "</span> Date: <span class='sizeEighteen'>" + endDate + "</span>");
    // $("#addEnd").attr("src","images/UpdateButton.png");
    //  $("#addEnd").attr("alt","update");
    }
    else
    {
        alert("Can not insert because of date discrepencies.");
    }
}
function hold(delay){
    var dfd = $.Deferred();

    setTimeout(function(){
        dfd.resolve();
    }, delay);

    return dfd.promise();
}
function addWayPt()
{
    var tempWDate = $("#tripWaypointDate").val();
    
    var startTemp = $("#tripStartDate").val().trim();
    var endTemp = $("#tripEndDate").val().trim();
    
    //checkdate true if date 1 later than date 2
    if(wayPoints.length < 8){
        
    
        if(startTemp != "" && endTemp != "" && checkDate(startTemp,tempWDate) < 1 && checkDate(endTemp,tempWDate) > -1)
        {   
            codeAddressWay("tripWaypoint");   
        }
        else
        {
            alert("Can not insert waypoint because of date discrepencies.");
        }
    }
    else{
          alert("Not allowed more than 8 waypoints due to Google API limitations. Sorry for the inconvenience");
    }
}

function addToWayPtList(location, date)
{
    // alert("ADDING: " + location + " | "+ date);
    var tempList = [];
    var tempLocList = [];
    var index = -1;
    for(var o = 0; o < wayDates.length; o++)
    {
        if(checkDate(wayDates[o],date) > 0){
            //THIS IS THE INDEX
            index = o;
            // alert(index);
            break;
        }
    }
    if(wayDates.length != 1 && index != -1){
        for(var n = 0; n < index; n++){
            tempList[n] = wayDates[n]
            tempLocList[n] = wayPoints[n];
        }
        tempList[index] = date;
        tempLocList[index] = location;
        for(var m = index; m < wayDates.length; m++){
            tempList[m+1] = wayDates[m]
            tempLocList[m+1] = wayPoints[m];
        }
    }
    else{
        if(index == -1){
            index = wayPoints.length;
            // alert(index);
            wayPoints[index] = location;
            wayDates[index] = date;
            tempList = wayDates;
            tempLocList = wayPoints;
            
        }
        else{
            tempList[0] = date;
            tempLocList[0] = location;
            index = 0;
            tempList[1] = wayDates[0];
            tempLocList[1] = wayPoints[0];
        }
    // alert("THIS");
    }
    wayDates = tempList;
    wayPoints = tempLocList;
    return index;
}

function addToServlet()
{
   // name = document.getElementById("tripName").value;
    var wayLocStr = "";
    var wayDateStr = "";
    var oWayLocStr = "";
    var oWayDateStr = "";
    for(var i = 0; i < wayDates.length;i++){
        wayLocStr += '&wayPtLocation=' + wayPoints[i];
        wayDateStr +='&wayPtDate=' + wayDates[i];
    }
    var ol = originalLocations.length;
    location.href ='./AddWaypointServlet?id=' + tripId + '&startLocation='+startLocation+'&endLocation='+endLocation+
    '&startDate='+startDate+'&endDate='+endDate + wayLocStr + wayDateStr + "&ol=" + ol;

}

function parseDateToPicker(date)
{
    var pickYear = date.substring(0,4);
    var pickMon = date.substring(5,7);
    var pickDay = date.substring(8);
    
    var strr = pickMon + "/" + pickDay + "/" + pickYear;
    
    return strr;
    
}


